package com.xiang.sql.service;

import java.util.List;

import jakarta.annotation.Resource;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiang.api.Util;
import com.xiang.api.entity.Message;
import com.xiang.sql.entity.User;
import com.xiang.sql.StaticSql;
import com.xiang.sql.entity.Group;
import com.xiang.sql.mapper.GroupMapper;

/**
 * 用户分组 服务实现类
 * 
 * @author mac-xiang
 */
@Service
public class GroupService extends ServiceImpl<GroupMapper, Group> {
  @Resource
  GroupMapper mapper;

  private QueryWrapper<Group> readWrapper(JSONObject p, User per) {
    QueryWrapper<Group> ret = Util.getQuery(p, Group.class);
    if (per != null && !per.per("用户分组查询")) {
      // ret.eq("`create`", per.id);
    }
    return ret;
  }

  private List<Group> getList(JSONObject p, User per) {
    return mapper.selectList(readWrapper(p, per));
  }

  private Page<Group> getPage(Page<Group> page, JSONObject p, User per) {
    return mapper.selectPage(page == null ? new Page<Group>(1, 100) : page, readWrapper(p, per));
  }

  public Group create(JSONObject p, User per) {
    if (per != null && per.per("用户分组创建")) {
      Group entity = Util.getEntity(p, Group.class);
      // entity.createTime = null;
      // entity.create = per.id;

      mapper.insert(entity);
      return entity;
    }
    throw new RuntimeException("没有权限");
  }

  public int update(JSONObject p, User per) {
    if (per != null && per.per("用户分组修改")) {
      Group entity = Util.getEntity(p, Group.class);
      QueryWrapper<Group> qw = Util.getQuery(p, Group.class);
      if (this.count(qw) > 10) {
        throw new RuntimeException("单次修改数量超过10条");
      }
      // entity.create = null;
      return mapper.update(entity, qw);
    }
    throw new RuntimeException("没有权限");
  }

  public Object read(JSONObject p, User per) {
    Page<Group> page = Util.getPage(p, Group.class);
    return page == null ? getList(p, per) : getPage(page, p, per);
  }

  public int delete(JSONObject p, User per) {
    if (per != null && per.per("用户分组删除")) {
      QueryWrapper<Group> q = Util.getQuery(p, Group.class);
      if (this.count(q) > 10) {
        throw new RuntimeException("删除数据的数量不能超过10条");
      }
      return mapper.delete(q);
    }
    throw new RuntimeException("没有权限");
  }

  public boolean exists(String id) {
    return this.count(new QueryWrapper<Group>().eq("id", id)) == 1;
  }

  public long count(List<String> ids) {
    long ret = 0;
    if (ids != null) {
      ret = this.count(new QueryWrapper<Group>().in("id", ids));
    }
    return ret;
  }

  public boolean isMerchant(String id) {
    if (id != null && id.equals("0")) {
      return true;
    } else if (id == null || id.length() < 1 || id.equals("2")) {
      return false;
    }
    String pid = getTopPid(id);
    return pid != null && (pid.equals("0") || pid.equals("1"));
  }

  public int getMerchantUserLiveByID(String id) {
    Group group = this.getById(id);
    if (group != null) {
      User user = StaticSql.service.user.getById(group.create);
      if (user == null) {
        mapper.clearCreateById(group.id);
      } else {
        String pid = getTopPid(id);
        if (pid != null && (pid.equals("1") || pid.equals("0"))) {
          return user.gLive();
        }
      }
    }
    return 0;
  }

  public String getTopPid(String id) {
    List<String> ids = new java.util.ArrayList<>();
    while (id != null) {
      if (ids.contains(id)) {
        ids.add(id);
        break;
      }
      ids.add(id);
      id = mapper.getPidById(id);
    }
    int ret = ids.size();
    if (ret > 0) {
      if (!ids.get(--ret).equals("") && ret > 0) {
        StaticSql.run.query(String.format("UPDATE `group` SET `pid` = '' WHERE `id` = '%s';", ids.get(ret - 1)));
      }
      return ids.get(ret > 0 ? --ret : 0);
    }
    return null;
  }

  public String pid(String id) {
    Group group = mapper.selectOne(new QueryWrapper<Group>().eq("id", id).select("id,pid"));
    if (group == null || Util.isEmpty(group.pid)) {
      return id;
    } else {
      return pid(group.pid);
    }
  }

  /** 创建商户 */
  public Message cg(JSONObject p, User per) {
    Message ret = new Message("用户不存在", true);
    if (per != null) {
      if (per.gid.equals("2")) {
        Group pg = this.getById(p.getString("gid"));
        if (pg == null || (!pg.pid.equals("1") && !pg.id.equals("0") && pg.pid.equals("0"))) {
          ret.message = "推荐商户不存在";
        } else {
          Group g = new Group();
          g.pid = "1";
          g.create = per.id;
          g.commission = 25;
          g.sid = pg.create;
          g.salesman = 5;
          g.state = 0;
          g.permission = pg.permission;
          g.name = "新店铺" + per.name;
          g.other = "{}";
          mapper.insert(g);
          per.gid = g.id;
          per.pid = pg.create;
          StaticSql.run.query(String.format("UPDATE `user` SET `gid` = '%s',`pid`='%s' WHERE `id` = '%s';",
              per.gid, per.pid, per.id));
          ret.message = "创建成功";
          ret.type = null;
          ret.data = per;
        }
      } else {
        ret.message = "您的账户禁止新建商户";
      }
    }
    return ret;
  }
}
